var ctx;
var firstLevel = 1;
var secondLevel = 2;
var province = '';
var city = '';
var district = '';

function setCtx(ctx) {
	this.ctx = ctx;
	initListener();  //添加区域监听事件
}

//省市区级联
function initListener() {
	$("#province").change(function () {
		province = $('#province').val();
		if (province != '') {
			$.ajax({
		        type : "GET",
		        url : ctx + "/district/getDistrictInfoByParentId",
		        cache : false,
		        dataType : 'json',
		        data : {
		        	parentId : province
		        },
		        success : function(data) {
		        	if (data.success) {
		                var result = "<option value='" + "'>--城市--</option>";
		                $.each(data.obj, function(index, item) {
		                    result += "<option id='" + item.regionName + "'" + " value='" + item.id + "'>" + item.regionName + "</option>";
		                });
		                $("#city").html('');
		                $("#city").append(result);
		                $("#city").change();
		            }
		        }
			});
		} else {
			var result = "<option value='" + "'>--城市--</option>";
			$("#city").html('');
            $("#city").append(result);
            $("#city").change();
		}
    });
	
    $("#city").change(function () {
    	city = $('#city').val();
    	if (city != ''){
    		$.ajax({
		        type : "GET",
		        url : ctx + "/district/getDistrictInfoByParentId",
		        cache : false,
		        dataType : 'json',
		        data : {
		        	parentId : city
		        },
		        success : function(data) {
		        	if (data.success) {
		        		var result = "<option value='" + "'>--区--</option>";
		                $.each(data.obj, function(index, item) {
		                    result += "<option id='" + item.regionName + "'" + " value='" + item.id + "'>" + item.regionName + "</option>";
		                });
		                $("#district").html('');
		                $("#district").append(result);
		            }
		        }
			});
    	} else {
    		var result = "<option value='" + "'>--区--</option>";
			$("#district").html('');
            $("#district").append(result);
    	}
    });
    
    $('#district').change(function() {
    	if ($('#district').val() != 0) {
    		district = $('#district').val();
    	}
    });
}

//验证小区名称
function checkCellName(){
	var cellName = $("#cellName").val();
	if(cellName == $("#cellName").attr("placeholder")){
		cellName = "";
	}
	
	if(cellName == null || cellName == ""){
		layer.tips('小区名称不能为空!', '#cellName', {
		    tips: 3,
			time:1000
		});
		return false;
	}else{
		return true;
	}
}

//验证省市区不能为空
function checkProvinceName(){
	var province = $("#province").val();

	var district = $("#district").val();
	if(province == null || province == ""){
		layer.tips('请选择省!', '#province', {
			tips: 3,
			time:1000
		});
		return false;
	}else{
		return true;
	}
}

//验证城市名称不能为空
function checkCityName(){
	var city = $("#city").val();
	if(city == null || city == ""){
		layer.tips('请选择市!', '#city', {
			tips: 3,
			time:1000
		});
	return false;
	}else{
		return true;
	}
}

//验证地区名称不能为空
function checkAreaName(){
	var district = $("#district").val();
	if(district == null || district == ""){
		layer.tips('请选择地区!', '#district', {
			tips: 3,
			time:1000
		});
	return false;
	}else{
		return true;
	}
}

//验证详细地址不能为空
function checkCellAddress(){
	var cellAddress = $("#cellAddress").val();
	if(cellAddress == $("#cellAddress").attr("placeholder")){
		cellAddress = "";
	}
	if(cellAddress == null || cellAddress == ""){
		layer.tips('详细地址不能为空!', '#cellAddress', {
			tips: 3,
			time:1000
		});
		return false;
	}else{
		return true;
	}
}

function isNumber(){
	var areaLand = $("#areaLand").val();
	var areaConstruction = $("#areaConstruction").val();
	var strP=/^\d+(\.\d+)?$/; 
	{ 
	if(areaLand == null || areaLand == ""){
		layer.tips('土地面积不能为空!', '#areaLand', {
			tips: 3,
			time:1000
		});
		return false; 
	}else if(!strP.test(areaLand)){
		layer.tips('面积只能是数字或小数!', '#areaLand', {
		    tips: 3,
			time:1000
		});
		return false;
	}else if(parseInt(areaLand) < parseInt(areaConstruction)){
		layer.tips('土地面积应大于等于建筑面积!', '#areaLand', {
			tips: 3,
			time:1000
		});
		return false;
	}else{
		return true; 
	} 
	}
}
	
function checkNumber(){
	var areaLand = $("#areaLand").val();
	var areaConstruction = $("#areaConstruction").val();
	var strP=/^\d+(\.\d+)?$/; 
	{ 
		if(areaConstruction == null || areaConstruction == ""){
			layer.tips('建筑面积不能为空!', '#areaConstruction', {
				tips: 3,
				time:1000
			});
			return false; 
		}else if(!strP.test(areaConstruction)){
			layer.tips('面积只能是数字或小数!', '#areaConstruction', {
				tips: 3,
				time:1000
			});
			return false;
		}else if(parseInt(areaLand) < parseInt(areaConstruction)){
			layer.tips('建筑面积应小于等于土地面积!', '#areaConstruction', {
				tips: 3,
				time:1000
			});
			return false;
		}else {
			return true; 
		} 
	}
}

//验证排序不能为空
function checkSort(){
	var reg = /^[0-9]*[1-9][0-9]*$/;
	var sort = $("#sort").val();
	if(sort == null || sort == ""){
		layer.tips('排序不能为空!', '#sort', {
			tips: 3,
			time:1000
		});
		return false;
	}else if(!reg.test(sort)){
		layer.tips('请输入正整数!', '#sort', {
			tips: 3,
			time:1000
		});
		return false;
	}else{
		return true;
	}
}

//保存或新增方法
function saveCellInfo() {
	var cellName = $('#cellName').val();
	var provinceId = $('#province').val();
	var cityId = $('#city').val();
	var areaId = $('#district').val();
	var cellAddress = $('#cellAddress').val();
	var areaLand = $('#areaLand').val();
	var areaConstruction = $('#areaConstruction').val();
	var sort = $('#sort').val();
	var operationCompanyId = $('#operationCompanyId').val();
	var proCompanyId = $('#proCompanyId').val();
	var disCompanyId = $('#disCompanyId').val();
	var cellId;
	if($('#cellId').val() != "" && $('#cellId').val() != undefined){
		cellId = $('#cellId').val();
	}else{
		cellId = 0;
	}
	var imageLogoUrl = $('#imageLogo').val();
	
	var container = ue.getContent();
	var menus = $("#selectRm").val();
	
	if(checkCellName() && checkProvinceName() && checkCityName() && checkAreaName() && checkCellAddress() && isNumber() && checkNumber() && checkSort()){
		var index1 = layer.load(1);
			$.ajax({
				type : "POST",
				url : ctx + "/cellInfo/saveOrUpdateCellInfo",
				cache : false,
				dataType : 'json',
				data: {
					cellName : cellName,
					provinceId : provinceId,
					cityId : cityId,
					areaId : areaId,
					cellAddress : cellAddress,
					areaLand : areaLand,
					areaConstruction : areaConstruction,
					sort : sort,
					container : container,
					cellId :cellId,
					operationCompanyId:operationCompanyId,
					proCompanyId:proCompanyId,
					disCompanyId:disCompanyId,
					longitude:$('#longitude').val(),
					latitude:$('#latitude').val(),
					logo : imageLogoUrl,
					menus:menus
				},
				success : function(result) {
					if (result.success) {
						
						layer.msg("操作成功",{
							icon: 1,
							time: 3000 //2秒关闭（如果不配置，默认是3秒）
						},function(){
							loadContent("/cellInfo/cellInfoList");
						});
					} else {
						layer.close(index1);
						layer.msg(result.msg,{
							icon: 2
						});
					}
				}
			});
	}

			
}

//返回上一页
function cancel(){
	loadContent("/cellInfo/cellInfoList");
}

var map;
function refreshMap(){
	// 百度地图API功能
	var longitude = $('#longitude').val();
	var latitude = $('#latitude').val();
	
	map = new BMap.Map("allmap");    // 创建Map实例
	if(longitude == '' || latitude == ''){
		map.centerAndZoom(new BMap.Point(114.305827, 30.568745), 12);  // 初始化地图,设置中心点坐标和地图级别
	}else{
		map.centerAndZoom(new BMap.Point(longitude, latitude), 12);  // 初始化地图,设置中心点坐标和地图级别
		var marker = new BMap.Marker(new BMap.Point(longitude, latitude)); // 创建点
		map.addOverlay(marker);            //增加点
	}
	
	//三维地图只有部分区域显示，所以将其隐藏，如要显示出来去掉mapTypes就好
	map.addControl(new BMap.MapTypeControl({mapTypes: [BMAP_NORMAL_MAP,BMAP_SATELLITE_MAP,BMAP_HYBRID_MAP]}));   //添加地图类型控件
	map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
	map.addEventListener("click", mapClick);
}

function mapClick(e){
	$('#longitude').val(e.point.lng);
	$('#latitude').val(e.point.lat);
	map.clearOverlays();   
	var marker = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat)); // 创建点
	map.addOverlay(marker);            //增加点
	
}


function chooseMenu (id){
	var selectMenu = parent.$('#selectRm').val();
	saveOrUpdateRoleMenu("小区功能权限",ctx + "/cellInfo/getCellMenu?cellId="+id + "&menus=" + selectMenu);
}

function saveOrUpdateRoleMenu(title , url){
	layer.open({
        type: 2,
        title: title,
        fix: false,
        shadeClose: true,
        scrollbar: false,
        maxmin: false,
        edit: true,
        closeBtn: 1,
        area: ['800px', '620px'],
        content: url,
        btn: ['确定', '取消']
	    ,yes: function(index, layero){ //或者使用btn1
	        //按钮【按钮一】的回调

	    	var iframeWin = window[layero.find('iframe')[0]['name']]; 
	    	iframeWin.selectOk();

	    },cancel: function(index){ //或者使用btn2
	        //按钮【按钮二】的回调
	    }
	});
}